import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register'),
  },
  {
    path: '/search/:keyword?',
    name: 'Search',
    component: () => import('@/views/Search'),
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('@/views/Detail'),
  },
  {
    path: '/addcartsuccess',
    name: 'AddCartSuccess',
    component: () => import('@/views/AddCartSuccess'),
  },
  {
    path: '/shopcart',
    name: 'ShopCart',
    component: () => import('@/views/ShopCart'),
  },
  {
    path: '/trade',
    name: 'Trade',
    component: () => import('@/views/Trade'),
  },
  {
    path: '/pay',
    name: 'Pay',
    component: () => import('@/views/Pay'),
  },
  {
    path: '/paysuccess',
    name: 'PaySuccess',
    component: () => import('@/views/PaySuccess'),
  },
  {
    path: '/center',
    name: 'Center',
    component: () => import('@/views/Center'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 }
  },
})

// 设置路由白名单,没有携带token也可以访问的页面
const whiteList = [
  'Home',
  'Login',
  'Register',
  'Search',
  'Detail',
  'ShopCart',
  'AddCartSuccess',
]
// 设置全局路由守卫

router.beforeEach((to, from, next) => {
  // 判断是否在白名单中
  // 判断是否有token
  if (whiteList.includes(to.name) || store.state.user.token) {
    next()
    return
  }
  // 不在白名单中,也没有token的,要跳转到login先登录,登录后跳转回原来的页面

  next({
    name: 'Login',
    query: {
      redirect: to.path,
    },
  })
})


export default router
